﻿using System;
using System.Linq;
using System.Web;
using Model_SSResourceManager;
using Presenter_SSResourceManager;

namespace WebView_SSResourceManager.Admin
{
    public partial class EditUser : System.Web.UI.Page, IViewEditUser
    {
        PresenterEditUser _presenter;

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new PresenterEditUser(this);
            if (!IsPostBack)
            {
                LoadUser();
            }
        }

        protected void Submit_OnClick(object sender, EventArgs e)
        {
            _presenter.Update();
        }

        private void LoadUser()
        {
            try
            {
                _presenter.FillFieldToEdit();
            }
            catch (Exception)
            {
                Response.Redirect("~/");
            }
        }

        public Guid GetUserId()
        {
            var query = HttpContext.Current.Request.Url.Query.Where(symbol => symbol != '?');
            return Guid.Parse(new string(query.ToArray()));
        }

        public void FillPageFields(User user)
        {
            lblLoginText.Text = user.Login;
            txtFirstName.Text = user.FirstName;
            txtLastName.Text = user.LastName;
            txtEmail.Text = user.Email;
            txtSkype.Text = user.Skype;
            ddlStatus.Text = user.Status.ToString();
            ddlRole.Text = user.Role.ToString();
            txtMessageTimeSpan.Text = user.MessageTimeSpan.ToString();
        }

        public User GatherPageFieldsInformation(User user)
        {
            user.Login = lblLoginText.Text;
            user.FirstName = txtFirstName.Text;
            user.LastName = txtLastName.Text;
            user.Email = txtEmail.Text;
            user.Skype = txtSkype.Text;
            UserStatus userStatus;
            Enum.TryParse(ddlStatus.Text, out userStatus);
            user.Status = userStatus;
            UserRoles userRole;
            Enum.TryParse(ddlRole.Text, out userRole);
            user.Role = userRole;
            user.MessageTimeSpan = TimeSpan.Parse(txtMessageTimeSpan.Text);
            return user;
        }
    }
}